import React, { useState } from 'react';
import { Button, Form, Alert } from 'react-bootstrap';

export default function AuthForm({ onLogin }) {
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: ''
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(`/api/${isLogin ? 'login' : 'register'}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });
      
      const data = await response.json();
      localStorage.setItem('token', data.token);
      onLogin();
    } catch (error) {
      alert(error.message);
    }
  };

  return (
    <div className="auth-container">
      <h2>{isLogin ? '登录' : '注册'}</h2>
      <Form onSubmit={handleSubmit}>
        {!isLogin && (
          <Form.Group className="mb-3">
            <Form.Label>用户名</Form.Label>
            <Form.Control
              type="text"
              placeholder="请输入用户名"
              value={formData.username}
              onChange={(e) => setFormData({ ...formData, username: e.target.value })}
            />
          </Form.Group>
        )}

        <Form.Group className="mb-3">
          <Form.Label>邮箱</Form.Label>
          <Form.Control
            type="email"
            placeholder="请输入邮箱"
            value={formData.email}
            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
          />
        </Form.Group>

        <Form.Group className="mb-3">
          <Form.Label>密码</Form.Label>
          <Form.Control
            type="password"
            placeholder="请输入密码"
            value={formData.password}
            onChange={(e) => setFormData({ ...formData, password: e.target.value })}
          />
        </Form.Group>

        <Button variant="primary" type="submit" className="w-100">
          {isLogin ? '登录' : '注册'}
        </Button>

        <div className="text-center mt-3">
          <Button variant="link" onClick={() => setIsLogin(!isLogin)}>
            {isLogin ? '没有账号？立即注册' : '已有账号？立即登录'}
          </Button>
        </div>
      </Form>
    </div>
  );
}
